package Redis

import (
	"fmt"
	"github.com/garyburd/redigo/redis" //git clone http://github.com/garyburd/redigo github.com/garyburd/redigo
	"log"
	"os"
	"queue/facade/frameLog"
	"queue/library/common"
	"strings"
	"time"
)

type RedisConf struct {
	host            string        //主机ip+端口 127.0.0.1:6379
	password        string        //密码
	netType         string        //连接类型 ： tcp 、udp
	Connect         redis.Conn    //实例创建的redis连接
	keepAlive       time.Duration //保持连接时长， 0表示长连接
	LogId           string
	LastUseTime     time.Time //最后一次调用开始的时间
	MethodsUseCount int       //记录连接的所有方法被总共被调用了多少次
	ConnectUseCount int       //记录这个链接使用了多少次
}

func (r *RedisConf) SetLogId(logId string) {
	r.LogId = logId
}

func NewRedisConnect(host, password, netType string, keepAlive time.Duration) (rc *RedisConf) {
	if strings.LastIndex(host, ":") == -1 {
		log.Fatal("host格式不对，必须包含主机和端口，例：", "127.0.0.1:6379")
	}
	cf := &RedisConf{host: host, password: password, netType: netType, keepAlive: keepAlive}
	conn, err := redis.Dial(cf.netType, cf.host, redis.DialKeepAlive(keepAlive))
	if err != nil {
		fmt.Println("redis.Dial err=", err)
		if conn != nil {
			conn.Close()
		}
		os.Exit(1)
	}
	//输入密码
	conn.Send("auth", cf.password)
	cf.Connect = conn
	return cf
}

func (r *RedisConf) Close() {
	r.Connect.Close()
}
func (r *RedisConf) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
	r.MethodsUseCount++
	r.LastUseTime = time.Now()
	timer := common.NewTimer()
	reply2, err := r.Connect.Do(commandName, args...)
	spendTime := timer.SpendMillisecond() //计算当前时间和 r.LastUseTime的时间差做为请求耗时，加入日志
	Logger.Write("INFO", fmt.Sprintf("logId[%s] spendTime[%d] action[%s] param", r.LogId, spendTime, commandName), args)
	if err != nil {
		frameLog.Error(fmt.Sprintf("logId[%s]  spendTime[%d] redis.%s err : %s", r.LogId, spendTime, commandName, err))
	}
	return reply2, err
}
func (r *RedisConf) Exper(keyName string, timeOut int) {

}
func (r *RedisConf) Get(keyName string) (string, error) {
	return redis.String(r.Do("Get", keyName))
}
func (r *RedisConf) Set(keyName string, value interface{}) (reply interface{}, err error) {
	return redis.String(r.Do("Set", keyName, value))
	//return nil , nil
}

func (r *RedisConf) HGet(keyName string, params interface{}) {

}
func (r *RedisConf) HSet(keyName, value string) {

}

func (r *RedisConf) ZGet(keyName string) {

}
func (r *RedisConf) ZSet(keyName, value string) {

}

func (r *RedisConf) LGet(keyName string) {

}
func (r *RedisConf) LSet(keyName, value string) {

}

func (r *RedisConf) TestErr(actionName string, params ...interface{}) (reply interface{}, err error) {
	return redis.String(r.Do(actionName, params...))
}
